import { ref } from 'vue'

// Token相关操作
const TOKEN_KEY = 'Admin-Token'
const USER_INFO_KEY = 'User-Info'
const TOKEN_EXPIRE_KEY = 'Token-Expire'

// 获取token
export function getToken() {
  return localStorage.getItem(TOKEN_KEY)
}

// 设置token
export function setToken(token) {
  localStorage.setItem(TOKEN_KEY, token)
  // 设置token过期时间为24小时
  const expireTime = new Date().getTime() + 24 * 60 * 60 * 1000
  localStorage.setItem(TOKEN_EXPIRE_KEY, expireTime.toString())
}

// 移除token
export function removeToken() {
  localStorage.removeItem(TOKEN_KEY)
  localStorage.removeItem(TOKEN_EXPIRE_KEY)
}

// 刷新token过期时间
export function refreshTokenExpire() {
  const expireTime = new Date().getTime() + 24 * 60 * 60 * 1000
  localStorage.setItem(TOKEN_EXPIRE_KEY, expireTime.toString())
}

// 检查token是否过期
export function isTokenExpired() {
  const expireTime = localStorage.getItem(TOKEN_EXPIRE_KEY)
  if (!expireTime) return true
  return new Date().getTime() > parseInt(expireTime)
}

// 用户信息相关操作
export function getUserInfo() {
  const userInfo = localStorage.getItem(USER_INFO_KEY)
  return userInfo ? JSON.parse(userInfo) : null
}

export function setUserInfo(userInfo) {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo))
}

export function removeUserInfo() {
  localStorage.removeItem(USER_INFO_KEY)
}

// 模拟登录
export function setMockLogin() {
  try {
    console.log('执行模拟登录...')
    // 设置模拟token
    const mockToken = 'mock-token-' + Math.random().toString(36).substr(2)
    setToken(mockToken)
    
    // 设置模拟用户信息
    setUserInfo({
      id: '1',
      name: 'Admin User',
      role: 'admin'
    })
    
    // 强制刷新token过期时间
    refreshTokenExpire()
    
    console.log('模拟登录成功:', { 
      mockToken: mockToken.substring(0, 15) + '...',
      expireTime: localStorage.getItem(TOKEN_EXPIRE_KEY),
      userInfo: getUserInfo()
    })
    
    return mockToken
  } catch (error) {
    console.error('模拟登录失败:', error)
    return null
  }
}

// 检查是否已登录
export function isLoggedIn() {
  const token = getToken()
  const tokenExpired = isTokenExpired()
  console.log('登录状态检查:', { 
    hasToken: !!token, 
    tokenExpired,
    token: token ? token.substring(0, 10) + '...' : null 
  })
  return token && !isTokenExpired()
}

// 导出登录状态响应式引用
export const loginState = ref(isLoggedIn()) 